import React, { Component } from 'react';
import { Form, Modal, InputNumber, Input, Button, Switch, Select, Image, Cascader } from 'antd'
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import TheImage from "@/components/TheImage";
import ThePagination from "@/components/ThePagination";
import TheUpload from '@/components/TheUpload'
import TheQueryForm from '@/components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend'
import { apiStoreInfoList } from '@/request/storeInfo'
import { apiDbAreaList } from '@/request/dbArea'
import { apiStoreDivideAdd, apiStoreDividePage,apiStoreDivideEdit, apiStoreDivideDel } from '@/request/storeDivide'

const { Option } = Select
class libraryManager extends Component {
    constructor() {
        super()
        this.queryFormRef = React.createRef()
        this.formRef = React.createRef()
        this.state = {
            title: '新增',
            loading: false,
            dataSource: [],
            columns: [
                {
                    title: "仓库ID",
                    dataIndex: "storeId",
                    key: "storeId"
                },
                {
                    title: "仓库名称",
                    dataIndex: "storeName",
                    key: "storeName",

                },
                {
                    title: "覆盖地区",
                    dataIndex: "provinceName",
                    key: "provinceName",
                    render: (text, record) => {
                        return record.provinceName 
                    }
                },
               
                // {
                //     title: "操作人",
                //     dataIndex: "updateUser",
                //     key: "updateUser"
                // },
                // {
                //     title: "操作时间",
                //     dataIndex: "updateTime",
                //     key: "updateTime"
                // },
                {
                    title: "操作",
                    render: (text, record) => {
                        return <>
                        {
                            record.provinceId=== 1?
                            <TheButton haspermi={['libraryManager:index:edit']} onClick={() => this.edit(record)}>编辑</TheButton>
                            :null
                        }
                            <TheButton haspermi={['libraryManager:index:del']} onClick={() => this.del(record)}>删除</TheButton>
                        </>
                    }
                },
            ],
            newColumns: [],
            pageData: {
                pageNo: 1,
                pageSize: 10
            },
            total: 0,

            searchOption: [
                { field: 'storeId', label: '仓库ID', placeholder: '请输入', required: false, rules: [], type: 'Input', defaultValue: '' },
            ],
            queryForm: {},
            form_show:true,
            provideList: [],
            storeList: [],
            storeDivideId:''

        }
    }
    async componentDidMount() {
        this.onColumnsFilter(this.state.columns)
        this.getData()
        this.getProvideList()
        this.getStoreList()


    }
    async getStoreList() {
        const res = await apiStoreInfoList({approvalStatus :'T',isProprietary:'Y',
            storeStatus :'Y'})
        if (res.code == 0) {
            this.setState({
                storeList: res.data
            })
        }
    }
    async getProvideList() {
        const res = await apiDbAreaList({ level: 1 })
        if (res.code == 0) {

            res.data.unshift({
                areaName: '默认区域',
                areaId: 1,
                isLeaf: false
            })
            this.setState({
                provideList: res.data.map(item => {
                    return {
                        ...item,
                        label: item.areaName,
                        value: item.areaId,
                        isLeaf: false
                    }
                })
            })
        }
    }

    getData(values) {
        this.setState({
            queryForm: values === undefined ? this.state.queryForm : { ...values }
        }, async () => {
            const { pageNo, pageSize } = this.state.pageData
            const { queryForm } = this.state
            const res = await apiStoreDividePage({ pageNo, pageSize, ...queryForm })
            if (res.code === 0) {
                this.setState({
                    dataSource: res.data,
                    total: res.totalCount
                })
            }
        })
    }
    loadData = async (selectedOptions) => {
        console.log(selectedOptions);
        const targetOption = selectedOptions[selectedOptions.length - 1];
        targetOption.loading = true; // load options lazily
        const res = await apiDbAreaList({ areaParentId: targetOption.value })
        if (res.code === 0) {
            targetOption.loading = false;
            targetOption.children = res.data.map(item => {
                return {
                    ...item,
                    label: item.areaName,
                    value: item.areaId,
                    isLeaf: true
                }
            });
            this.setState({
                provideList: this.state.provideList.map(item => {
                    if (item.value === targetOption.value) {
                        item = targetOption
                    }
                    return item
                })
            })

        }

    }
    edit(record){
        this.setState({
            storeDivideId:record.storeDivideId,
            isModalOpen: true,
            title: '编辑'
        },()=>{
            this.formRef.current.setFieldsValue({
                storeId:record.storeId,
                areaIds:[record.provinceId],
            })
        })
    }
    add() {
        this.setState({
            isEdit: false,
            isModalOpen: true,
            title: '划分辖区'
        })
    }
    handleOk = async () => {
        const values = this.formRef.current.getFieldsValue()
        let params = values.areaIds.map(item=>{
            return {
                storeId:values.storeId,
                provinceId:item
            }
        })
        if(this.state.storeDivideId){
            params = {
                storeId:values.storeId,
                storeDivideId:this.state.storeDivideId
            }
            const res = await apiStoreDivideEdit(params)
            if (res.code === 0) {
                this.handleCancel()
                this.pageChange(1, 10)
            }
        }else{
            const res = await apiStoreDivideAdd(params)
            if (res.code === 0) {
                this.handleCancel()
                this.pageChange(1, 10)
            }
        }
       

    };
    handleCancel = () => {
        this.formRef.current.resetFields()
        this.setState({
            isModalOpen: false,
            brandList: [],
            storeDivideId:''
        })
    };

    del = record => {
        React.$confirm({
            title: "警告",
            content: `确定删除此信息吗？`,
            onOk: async () => {
                const res = await apiStoreDivideDel({ storeDivideId: record.storeDivideId })
                if (res.code === 0) {
                    this.pageChange(1, 10)
                }
            }
        });
    }
    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData:{
                pageNo,pageSize
            }
        })
        this.getData()
    }
    selectFilter(input, option) {
        const result = option.children.toLowerCase().includes(input.toLowerCase()) 
        return result
    }
    onTableRefresh() {
        this.getData()
    }
    onColumnsFilter(value) {
        this.setState({
            newColumns: value
        })
    }
    onReset() {
        this.setState({
            queryForm: {}
        }, () => {
            this.pageChange(1, 10)
        })
    }
    render() {
        const { isEdit, brandList,storeDivideId, classifyList, storeList, provideList, cityData, brandInfo, loading, dataSource, columns, pageData, total, newColumns, isModalOpen, form_show, title, fileList, searchOption } = this.state
        const { pageNo, pageSize } = pageData
        return (
            <div className={"p-layout-box configuration"}>
                <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show}  onReset={(values) => this.onReset(values)} option={searchOption} onGetValues={(values) => this.getData(values)} >
                </TheQueryForm>
                <TheTableExtend
                    columns={columns}
                    onFormTrigger={() => this.setState({ form_show: !this.state.form_show })}
                    onTableRefresh={() => this.onTableRefresh()}
                    onColumnsFilter={(value) => this.onColumnsFilter(value)}
                >
                    <TheButton type={'primary'} size={'middle'} haspermi={['libraryManager:index:Add']}
                        onClick={() => { this.add() }}>划分辖区</TheButton>
                </TheTableExtend>

                <TheTable bordered loading={loading} dataSource={dataSource} columns={newColumns} />
                <ThePagination pageNo={pageNo} pageSize={pageSize} total={total}
                    pageChange={this.pageChange}
                />
                <Modal title={title} visible={isModalOpen} footer={null} onOk={() => this.handleOk()} onCancel={() => this.handleCancel()}>
                    <Form ref={this.formRef}
                        onFinish={(values) => this.handleOk(values)}
                        labelCol={{
                            span: 4,
                        }}
                        wrapperCol={{
                            span: 16,
                        }}
                    >
                        <Form.Item
                            name="storeId"
                            label={'仓库名称'}
                            rules={[{ required: true }]}>
                            <Select >
                                {
                                    storeList.map(item => <Option value={item.storeId}>{item.storeName}</Option>)
                                }

                            </Select>
                        </Form.Item>
                        <Form.Item
                            name="areaIds"
                            label={'覆盖地区'}
                            rules={[{ required: true }]}>
                            <Select disabled={storeDivideId} mode="multiple"
                            
                            optionFilterProp="children"
                            filterOption={(input, option) => this.selectFilter(input, option)}
                            >
                                {
                                    provideList.map(item => <Option value={item.areaId }>{item.areaName}</Option>)
                                }
                            </Select>
                        </Form.Item>
                        {/* <Form.Item
                            name="brandClassifyId"
                            label={'仓库所在地'}
                            rules={[{ required: true }]}>
                            <Cascader options={provideList} loadData={this.loadData} changeOnSelect />
                        </Form.Item> */}
                        {/* <Form.Item
                            name="brandId"
                            label={'设置为虚拟仓库'}
                            rules={[{ required: true }]}>
                            <Switch defaultChecked />
                        </Form.Item>
                        <Form.Item
                            name="brandId"
                            label={'设置为地区门店仓'}
                            rules={[{ required: true }]}>
                            <Switch defaultChecked />
                        </Form.Item>
                        <Form.Item
                            name="brandId"
                            label={'设置为默认发货仓'}
                            rules={[{ required: true }]}>
                            <Switch defaultChecked />
                        </Form.Item> */}

                        <Form.Item
                            wrapperCol={{
                                offset: 8,
                                span: 16,
                            }}
                        >
                            <Button type="default" onClick={() => this.handleCancel()} style={{ 'marginRight': 20 }}>
                                取消
                            </Button>
                            <Button type="primary" htmlType="submit">
                                确定
                            </Button>
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        )
    }
}

export default libraryManager